const TerserPlugin = require('terser-webpack-plugin')
const afs_proxy_config = require('./src/config/afs_proxy_config')
const afs_projectConfig = require('./src/config/afs_project_config')
const path = require('path')

const resolve = dir => {
    return path.join(__dirname, dir)
}
const BASE_URL = process.env.NODE_ENV === 'dev' ? '' : '/'
const CompressionWebpackPlugin = require('compression-webpack-plugin')
const productionGzipExtensions = ['js', 'css']
const Timestamp = new Date().getTime();
let afsInfo = {
    version:'1.0',
    name:process.argv[4],
    env:process.argv.length>=6?process.argv[6]:'dev'
}
let afsProjectInfo = {
    title: afs_projectConfig[afsInfo.name].title,
    webKey: afs_projectConfig[afsInfo.name].webKey,
    useI18n: afs_projectConfig[afsInfo.name].useI18n,
    apiUri:afsInfo.env==='dev'?'':(afs_projectConfig[afsInfo.name].apiUri[afsInfo.env]),
    webSocketUri:(afs_projectConfig[afsInfo.name].webSocketUri[afsInfo.env]),
    softPhone:(afs_projectConfig[afsInfo.name].softPhone)?afs_projectConfig[afsInfo.name].softPhone[afsInfo.env]:{api:'no-define',ws:'no-define'},
    topHeaderComponent:(afs_projectConfig[afsInfo.name].topHeaderComponent)?(afs_projectConfig[afsInfo.name].topHeaderComponent):[],
    homeName: afs_projectConfig[afsInfo.name].homeName,
    path:afs_projectConfig[afsInfo.name].path,
    name:afsInfo.name,
    menuLocation:afs_projectConfig[afsInfo.name].menuLocation,
    theme:afs_projectConfig[afsInfo.name].theme,
    componentRequestUri:afs_projectConfig[afsInfo.name].componentRequestUri,
    sysDate:afs_projectConfig[afsInfo.name].sysDate
};
module.exports = {
    css: {
        loaderOptions: {
            less: {
                javascriptEnabled: true
            }
        },
        extract: {
            filename: `css/[name].${Timestamp}.css`,
            chunkFilename:`css/[name].${Timestamp}.css`
        },
        sourceMap: false,
        modules: false
    },
    publicPath: BASE_URL,
    lintOnSave: true,
    outputDir: 'dist/'+process.argv[4],
    chainWebpack: config => {
        // key,value自行定义，比如.set('@@', resolve('src/components'))
        config.resolve.alias
            .set('@', resolve('src'))
            .set('_c', resolve('src/components'))
            .set('_p', resolve('src/projects'));
        config
            .plugin('define')
            .tap(args => {
                args[0]._AFS_CONFIG = JSON.stringify(afsInfo)
                args[0]._AFS_PROJECT_CONFIG = JSON.stringify(afsProjectInfo)
                return args
            });
        config
            .module
            .rule('vue')
            .test(function (name) {
                name = name.replace(/\\/g,'/');
                if(name.endsWith('foo.vue')){
                    return true;
                }
                if(name.endsWith('vue')){
                    if(name.endsWith("src/App.vue")){
                        return true;
                    }
                    if(name.indexOf('src/projects/basic')>-1||name.indexOf('/node_modules/')>-1||name.indexOf('src/components')>-1||name.indexOf('src/projects/'+afsProjectInfo.path)>-1){
                        return true;
                    }
                    if(process.env.NODE_ENV==='development'&&name.indexOf("src/demo")>-1){
                        return true;
                    }
                }
                if(name.endsWith('vue')){
                    // console.log("不打包["+name+"]")
                }
                return false;
            })
            .end();
        config.module.rule('compile')
            .test(function (name){
                // console.log("babel-loader process=>"+name)
                return name.endsWith('js')&&!name.endsWith('fullcalendar.js');
            })
            .include
            .add(resolve('src'))
            .end()
            .use('babel')
            .loader('babel-loader')
            .options({
                presets: [
                    ['@babel/preset-env', {
                        modules: false
                    }]
                ]
            });
    },
    // 设为false打包时不生成.map文件
    productionSourceMap: (afsInfo.env=='dev'||afsInfo.env=='test')?true:false,
    //打包采用gzip
    configureWebpack: config => {
        if (process.env.NODE_ENV !== 'development') {
            // 生产环境
            config.plugins.push(
                new CompressionWebpackPlugin({
                    filename: '[path].gz[query]',
                    algorithm: 'gzip',
                    test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'),
                    threshold: 10240,
                    minRatio: 0.8
                })
            );
            config.optimization.minimizer=[
                new TerserPlugin({
                    sourceMap:false,
                    terserOptions:{
                        compress:{
                            drop_console : true
                        }
                    }
                })
            ];
            config.output.filename=`js/[name].${Timestamp}.js`;
            config.output.chunkFilename=`js/[name].${Timestamp}.js`;
            config.optimization.splitChunks = {
                chunks: 'all',
                minSize: 300,
                maxSize: 512000 * 2,
                maxAsyncRequests: 5,
                maxInitialRequests: 3,
                cacheGroups: {
                    vendors: {
                        name: "chunk-vendors",
                        test: /[\\/]node_modules[\\/]/,
                        chunks: "all",
                        priority: 5,
                        reuseExistingChunk: true,
                    },
                    common: {
                        name: "chunk-commons",
                        test: /[\\/]src[\\/]compoments[\\/]/,
                        minChunks: 2,
                        chunks: 'all',
                        priority: 3,
                        reuseExistingChunk: true,
                    },
                    default: {
                        minChunks: 2,
                        priority: -26,
                        reuseExistingChunk: true
                    }
                },
            }
        } else {
            console.log('开发启动')
        }
    }
    , devServer: {
        proxy: {...afs_proxy_config.getProxyInfo()},
        disableHostCheck: true,
        headers: {
            'Access-Control-Allow-Origin': '*',
            "Access-Control-Allow-Headers":"*",
            "Access-Control-Allow-Methods":"PUT,POST,GET,DELETE,OPTIONS",
            "Cross-Origin-Resource-Policy":"cross-origin"
        },
        allowedHosts: [
            '*'
        ]
    }
}
